package com.zimi.service;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zimi.mapper.*;
import com.zimi.model.*;
import com.zimi.util.FormElementUtil;
import com.zimi.util.StrUtil;
import com.zimi.util.UserUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WfSystaskKeyService{

    private final WfSystaskKeyMapper wfSystaskKeyMapper;
    private final WfSystaskKeyVOMapper wfSystaskKeyVOMapper;
    private final WfTaskMapper wfTaskMapper;
    private final WfSystaskMapper wfSystaskMapper;
    private final WfWorkflowMapper wfWorkflowMapper;
    private final WfModuleMapper wfModuleMapper;
    private final WfActivityMapper wfActivityMapper;
    private final WfActivityLineMapper wfActivityLineMapper;
    private final SysUserMapper sysUserMapper;
    private final WfEntrustVOMapper wfEntrustVOMapper;
    private final WfDictionaryMapper wfDictionaryMapper;
    private final ExpenseReimbursementMapper expenseReimbursementMapper;
    private final SysOrgExtendMapper sysOrgExtendMapper;

    final String ONE = "one";//是001活动保存以后提交
    final String TWO = "two";//是审批提交

    final int STATE_KLSLKS = 1;//办理中
    final int STATE_OVER = 2;//已办结
    final int STATE_REVOKE = 3;//被撤销
    final int STATE_RETRIEVE = 4;//已取回
    final String END = "end";

    final int DONEONE = 1;  //提交
    final int DONETWO = 2;//退回
    final int DONETHREE = 3;//撤销

    final int WFTASKONE = 1;//待办状态：1-有效；2-无效
    final int WFTASKTWO = 2;

    final int SYSTASKONE = 1;//环节状态：1-办理中；2-已办理
    final int SYSTASKTWO = 2;

    final String OPERATION_ONE = "1";//操作类型：1-串行，2-并行, 3-抢占, 4-协作
    final String OPERATION_TWO = "2";
    final String OPERATION_THREE = "3";
    final String OPERATION_FOUR = "4";

    //参与类型：1-单人，2-多人
    final String ACTYPEONE = "1";
    final String ACTYPETWO = "2";

    final String ACTIVITY_TYPE_ORG = "1";       //机构
    final String ACTIVITY_TYPE_POST = "3";      //岗位
    final String ACTIVITY_TYPE_DUTY = "4";      //职务
    final String ACTIVITY_TYPE_USER = "5";      //用户
    final String ACTIVITY_TYPE_LOGIC = "6";     //计算
    final String ACTIVITY_TYPE_SEGMENT = "7";   //指定环节

    WfSystaskKey wfSystaskKey = new WfSystaskKey();
    WfSystask wfSystaskNow = new WfSystask();
    WfSystask wfSystaskNext = new WfSystask();
    WfTask wfTask = new WfTask();
    WfTaskTest wfTaskTe = new WfTaskTest();

    @Autowired
    public WfSystaskKeyService(SysUserMapper sysUserMapper, WfSystaskKeyMapper wfSystaskKeyMapper, ExpenseReimbursementMapper expenseReimbursementMapper, WfSystaskKeyVOMapper wfSystaskKeyVOMapper, WfTaskMapper wfTaskMapper, WfDictionaryMapper wfDictionaryMapper, WfSystaskMapper wfSystaskMapper, WfWorkflowMapper wfWorkflowMapper, WfModuleMapper wfModuleMapper, SysOrgExtendMapper sysOrgExtendMapper, WfActivityMapper wfActivityMapper, WfActivityLineMapper wfActivityLineMapper, WfEntrustVOMapper wfEntrustVOMapper, WfActivityAuthorityMapper wfActivityAuthorityMapper, SysUserVOMapper sysUserVOMapper) {
        this.sysUserMapper = sysUserMapper;
        this.wfSystaskKeyMapper = wfSystaskKeyMapper;
        this.expenseReimbursementMapper = expenseReimbursementMapper;
        this.wfSystaskKeyVOMapper = wfSystaskKeyVOMapper;
        this.wfTaskMapper = wfTaskMapper;
        this.wfDictionaryMapper = wfDictionaryMapper;
        this.wfSystaskMapper = wfSystaskMapper;
        this.wfWorkflowMapper = wfWorkflowMapper;
        this.wfModuleMapper = wfModuleMapper;
        this.sysOrgExtendMapper = sysOrgExtendMapper;
        this.wfActivityMapper = wfActivityMapper;
        this.wfActivityLineMapper = wfActivityLineMapper;
        this.wfEntrustVOMapper = wfEntrustVOMapper;
        WfActivityAuthorityMapper wfActivityAuthorityMapper1 = wfActivityAuthorityMapper;
        SysUserVOMapper sysUserVOMapper1 = sysUserVOMapper;
    }

    //自动插入创建人、创建时间
    public WfSystaskKey autoCreateUserAndTime(WfSystaskKey record) {
        SysUser currentUser = UserUtil.getUser();
        DateTime now = new DateTime();
        if (record.getCreateUser() == null) {
            record.setCreateUser(currentUser.getId());
        }
        if (record.getCreateTime() == null) {
            record.setCreateTime(now);
        }

        return record;
    }

    //自动插入修改人、修改时间
    public WfSystaskKey autoUpdateUserAndTime(WfSystaskKey record) {
        DateTime now = new DateTime();
        if (record.getUpdateTime() == null) {
            record.setUpdateTime(now);
        }

        return record;
    }

    public Date getNow() {
        DateTime now = new DateTime();
        return now;
    }

    public Integer getUserId() {
        SysUser user = UserUtil.getUser();
        return user.getId();
    }

    public int deleteByPrimaryKey(Integer id) {
        return wfSystaskKeyMapper.deleteByPrimaryKey(id);
    }

    public int insert(WfSystaskKey record) {
        record = autoCreateUserAndTime(record);
        return wfSystaskKeyMapper.insert(record);
    }

    public int insertSelective(WfSystaskKey record) {
        record = autoCreateUserAndTime(record);
        return wfSystaskKeyMapper.insertSelective(record);
    }

    public WfSystaskKey selectByPrimaryKey(Integer id) {
        return wfSystaskKeyMapper.selectByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(WfSystaskKey record) {
        record = autoUpdateUserAndTime(record);
        return wfSystaskKeyMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(WfSystaskKey record) {
        record = autoUpdateUserAndTime(record);
        return wfSystaskKeyMapper.updateByPrimaryKey(record);
    }

    public List<WfSystaskKey> selectAll(WfSystaskKey record) {
        return wfSystaskKeyMapper.selectAll(record);
    }

    public List<WfSystaskKeyVO> selectMyDoneTask(WfSystaskKey record) {
        return wfSystaskKeyMapper.selectMyDoneTask(record);
    }

    /*
     * 提交
     * */
    @Transactional
    public List<WfTargetActivityAndOperators> saveSubmit(WfTaskTest wfTaskTest) throws Exception {
        List<WfTargetActivityAndOperators> wfTargets = null;
        wfTaskTe = wfTaskTest;
        if (!"".equals(wfTaskTest.getTaskId()) && wfTaskTest.getTaskId() != null) {
            //判断提交状态
            String one = getOneActivity(Integer.parseInt(wfTaskTest.getTaskId()));
            if (ONE.equals(one)) {
                //是001活动保存以后提交
                wfTargets = saveOneSaveSubmit(wfTaskTest);

            } else {
                //是审批提交
                wfTargets = saveTwoSubmit(wfTaskTest);
            }

        } else {
            //001活动未保存提交
            wfTargets = saveOneSubmit(wfTaskTest);
        }

        return wfTargets;
    }

    /**
     * 保存
     */
    @Transactional
    public Map<String, Integer> saveSave(WfTaskTest wfTaskTest) {
        /*
         * 判断发起人保存
         *       审批环节保存
         * */
        wfSystaskNow = new WfSystask();
        wfSystaskKey = new WfSystaskKey();
        wfTask = new WfTask();
        if (!"".equals(wfTaskTest.getTaskId()) && wfTaskTest.getTaskId() != null) {
            //发起人再保存也是审批保存
            wfSystaskNow = wfSystaskMapper.selectByPrimaryKey(Integer.valueOf(wfTaskTest.getTaskId()));
            wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
            wfSystaskNow.setUpdateTime(getNow());
            wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
            wfTask = new WfTask();
            wfTask.setSysTaskId(Integer.valueOf(wfTaskTest.getTaskId()));
            List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
            for (WfTask wfTask1 : wfTasks) {
                wfTask.setId(wfTask1.getId());
                wfTask.setWfTaskRecord(wfTaskTest.getWfRecord());
                wfTask.setUpdateTime(getNow());
                wfTask.setUpdateUser(getUserId());
                wfTaskMapper.updateByPrimaryKeySelective(wfTask);
            }
        } else {
            //发起人保存
            wfSystaskKey.setWfId(Integer.valueOf(wfTaskTest.getWfId()));
            WfWorkflow wfWorkflow = new WfWorkflow();
            wfWorkflow = getWorkflow(Integer.valueOf(wfTaskTest.getWfId()));
            wfSystaskKey.setModuleId(wfWorkflow.getModuleId());
            wfSystaskKey.setWfTitle(wfWorkflow.getWfTitle());
            wfSystaskKey.setFormId(wfWorkflow.getFormEditId());
            wfSystaskKey.setSysTaskKeyState(STATE_KLSLKS);
            insertSelective(wfSystaskKey);
            wfSystaskKey.setId(wfSystaskKeyMapper.lastInsertId());
            wfSystaskNow.setSysTaskKeyId(wfSystaskKey.getId());
            wfSystaskNow.setActivityId(Integer.valueOf(wfTaskTest.getActivityId()));
            wfSystaskNow.setSysTaskState(SYSTASKTWO);
            wfSystaskNow.setWfTitle(wfWorkflow.getWfTitle());
            wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
            SysUser user = UserUtil.getUser();
            wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
            wfSystaskNow.setTaskTodoUser(String.valueOf(user.getId()));
            wfSystaskNow.setTaskDoneType(DONEONE);
            wfSystaskNow.setCreateTime(getNow());
            wfSystaskMapper.insertSelective(wfSystaskNow);
            wfSystaskNow.setId(wfSystaskMapper.lastInsertId());
            wfTask.setActivityId(Integer.valueOf(wfTaskTest.getActivityId()));
            wfTask.setSysTaskId(wfSystaskNow.getId());
            wfTask.setWfTitle(wfSystaskNow.getWfTitle());
            wfTask.setWfTaskRecord(wfSystaskNow.getSysTaskRecord());
            wfTask.setWfTaskState(WFTASKONE);
            wfTask.setSysTaskKeyId(wfSystaskKey.getId());
            wfTask.setTaskExecutor(user.getId());
            wfTask.setCreateTime(getNow());
            wfTaskMapper.insertSelective(wfTask);
            wfSystaskKey.setCurrentSysTaskId(wfSystaskNow.getId());
            updateByPrimaryKeySelective(wfSystaskKey);
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("keyId", wfSystaskKey.getId());
        map.put("taskId", wfSystaskNow.getId());
        return map;
    }

    /**
     * 提交时判断是否是001活动保存以后提交 还是审批提交
     * 拿到的id如果为空一定是001活动提交
     * 拿到的id如果不为空
     * 可能是001活动保存以后提交   可能是审批提交
     */
    @Transactional
    public String getOneActivity(int id) {
        String one = "";
        WfSystask wfSystask = new WfSystask();
        wfSystask = wfSystaskMapper.selectByPrimaryKey(id);
        int recentId = 0;//上一环节id
        if (wfSystask.getRecentlySysTaskId() != null) {
            recentId = wfSystask.getRecentlySysTaskId();
        }
        if (recentId == 0) {
            one = ONE;
        } else {
            one = TWO;
        }
        return one;
    }

    //是001活动保存以后提交
    @Transactional
    public List<WfTargetActivityAndOperators> saveOneSaveSubmit(WfTaskTest wfTaskTest) throws Exception {
        SysUser user = UserUtil.getUser();
        wfSystaskNow = wfSystaskMapper.selectByPrimaryKey(Integer.valueOf(wfTaskTest.getTaskId()));
        wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
        wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
        wfSystaskNow.setSysTaskState(SYSTASKTWO);
        wfSystaskKey = selectByPrimaryKey(wfSystaskNow.getSysTaskKeyId());
        List<WfTargetActivityAndOperators> wfTargets = getSub(wfTaskTest);
        return wfTargets;
    }

    //是审批提交
    @Transactional
    public List<WfTargetActivityAndOperators> saveTwoSubmit(WfTaskTest wfTaskTest) throws Exception {
        SysUser user = UserUtil.getUser();
        wfSystaskNow = new WfSystask();
        wfSystaskNow = wfSystaskMapper.selectByPrimaryKey(Integer.valueOf(wfTaskTest.getTaskId()));
        wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
        wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
        wfSystaskNow.setSysTaskState(SYSTASKTWO);
        wfSystaskKey = selectByPrimaryKey(wfSystaskNow.getSysTaskKeyId());
        List<WfTargetActivityAndOperators> wfTargets = getSub(wfTaskTest);
        return wfTargets;

    }

    //001活动未保存提交
    @Transactional
    public List<WfTargetActivityAndOperators> saveOneSubmit(WfTaskTest wfTaskTest) throws Exception {
        wfSystaskKey = new WfSystaskKey();
        wfSystaskKey.setWfId(Integer.valueOf(wfTaskTest.getWfId()));
        WfWorkflow wfWorkflow = new WfWorkflow();
        wfWorkflow = getWorkflow(Integer.valueOf(wfTaskTest.getWfId()));
        wfSystaskKey.setModuleId(wfWorkflow.getModuleId());
        wfSystaskKey.setWfTitle(wfWorkflow.getWfTitle());
        wfSystaskKey.setCurrentSysTaskId(Integer.valueOf(wfTaskTest.getActivityId()));
        wfSystaskKey.setFormId(wfWorkflow.getFormEditId());
        wfSystaskKey.setSysTaskKeyState(STATE_KLSLKS);
        insertSelective(wfSystaskKey);
        wfSystaskKey.setId(wfSystaskKeyMapper.lastInsertId());
        wfSystaskNow = new WfSystask();
        wfSystaskNow.setSysTaskKeyId(wfSystaskKey.getId());
        wfSystaskNow.setActivityId(Integer.valueOf(wfTaskTest.getActivityId()));
        wfSystaskNow.setSysTaskState(SYSTASKTWO);
        wfSystaskNow.setWfTitle(wfWorkflow.getWfTitle());
        wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
        SysUser user = (SysUser) UserUtil.getUser();
        wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
        wfSystaskNow.setTaskTodoUser(String.valueOf(user.getId()));
        wfSystaskNow.setTaskDoneType(DONEONE);
        wfSystaskNow.setCreateTime(getNow());
        wfSystaskMapper.insertSelective(wfSystaskNow);
        wfSystaskNow.setId(wfSystaskMapper.lastInsertId());
        List<WfTargetActivityAndOperators> wfTargets = getSub(wfTaskTest);
        return wfTargets;
    }

    /**
     * todo
     *
     * @param wfTaskTest
     * @return selectById
     * @ 提交
     * 判断当前活动是不是多人串行、多人并行
     */
    @Transactional
    public List<WfTargetActivityAndOperators> getSub(WfTaskTest wfTaskTest) throws Exception {
        String optionType = getOperationType(Integer.valueOf(wfTaskTest.getActivityId()));
        List<WfTargetActivityAndOperators> wfTargets = new ArrayList<WfTargetActivityAndOperators>();
        SysUser user = UserUtil.getUser();
        List list = new ArrayList();
        if (OPERATION_ONE.equals(optionType)) {
            //串行
            Integer nId = Integer.valueOf(wfTaskTest.getTaskId());
            wfSystaskNow = wfSystaskMapper.selectById(nId);
            String startUser;
            wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
            wfSystaskNow.setSysTaskState(SYSTASKTWO);
            String id = wfSystaskNow.getTaskTodoUser();
            String[] ids = id.split(",");
            int index = ids.length;
            if (wfSystaskNow.getTaskDoneUser() == null || "".equals(wfSystaskNow.getTaskDoneUser())) {
                startUser = "";
                wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
            } else {
                startUser = wfSystaskNow.getTaskDoneUser();
                wfSystaskNow.setTaskDoneUser(wfSystaskNow.getTaskDoneUser() + "," + user.getId());
            }
            if (id.length() == wfSystaskNow.getTaskDoneUser().length()) {
                wfTargets = getAllNextTargetOperator(wfSystaskNow, wfTaskTest.getWfRecord());
                if (wfTargets.size() != 1) {
                    wfSystaskNow.setTaskDoneUser(startUser);
                }
                saveSub(wfTargets);
            } else {
                int index1 = 0;
                for (int i = 0; i < ids.length; i++) {
                    if (ids[i].equals((user.getId().toString()) + "")) {
                        index1 = i;
                    }
                }
                wfTask = new WfTask();
                wfTask.setSysTaskId(wfSystaskNow.getId());
//                wfTask.setTaskExecutor(user.getId());
                List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
                wfTask.setWfTaskRecord(wfTaskTest.getWfRecord());
                wfTask.setWfTaskState(WFTASKTWO);
                for (WfTask wfTask1 : wfTasks) {
                    wfTask.setId(wfTask1.getId());
                    wfTask.setUpdateTime(getNow());
                    wfTask.setUpdateUser(getUserId());
                    wfTaskMapper.updateByPrimaryKeySelective(wfTask);
                }
                wfTask = new WfTask();
                wfTask.setWfTaskRecord(wfTaskTest.getWfRecord());
                wfTask.setSysTaskId(wfSystaskNow.getId());
                wfTask.setSysTaskKeyId(wfSystaskNow.getSysTaskKeyId());
                wfTask.setWfTaskState(WFTASKONE);
                wfTask.setActivityId(Integer.valueOf(wfTaskTest.getActivityId()));
                wfTask.setTaskExecutor(Integer.valueOf(ids[index1 + 1]));
                wfTask.setWfTitle(wfSystaskNow.getWfTitle());
                wfTask.setCreateTime(getNow());
                wfSystaskNow.setUpdateTime(getNow());
                wfTask.setUpdateUser(getUserId());
                wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
                wfTaskMapper.insertSelective(wfTask);
                SysUser sysUser = new SysUser();
                WfTargetActivityAndOperators wfTargetActivityAndOperators = new WfTargetActivityAndOperators();
                list.add("chuan");
                sysUser = sysUserMapper.selectById(wfTask.getTaskExecutor());
                list.add(sysUser);
                wfTargetActivityAndOperators.setOperatorList(list);
                wfTargets.add(wfTargetActivityAndOperators);
            }

        } else if (OPERATION_TWO.equals(optionType)) {
            //并行
            wfSystaskNow = new WfSystask();
            wfSystaskNow = wfSystaskMapper.selectById(Integer.valueOf(wfTaskTest.getTaskId()));
            wfSystaskNow.setSysTaskRecord(getTaskRecord(wfSystaskNow.getSysTaskRecord(), wfTaskTest.getWfRecord()));
            String id = wfSystaskNow.getTaskTodoUser();
            String userId;
            String startUser;
            wfSystaskNow.setSysTaskState(SYSTASKTWO);
            if (wfSystaskNow.getTaskDoneUser() == null || "".equals(wfSystaskNow.getTaskDoneUser())) {
                userId = String.valueOf(user.getId());
                startUser = "";
                wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
            } else {
                startUser = wfSystaskNow.getTaskDoneUser();
                userId = wfSystaskNow.getTaskDoneUser() + "," + user.getId();
                wfSystaskNow.setTaskDoneUser(wfSystaskNow.getTaskDoneUser() + "," + user.getId());
            }
            if (id.length() == userId.length()) {
                //按照正常提交走
                wfTargets = getAllNextTargetOperator(wfSystaskNow, wfTaskTest.getWfRecord());
                if (wfTargets.size() != 1) {
                    wfSystaskNow.setTaskDoneUser(startUser);
                }
                saveSub(wfTargets);
            } else {
                wfTask = new WfTask();
                wfTask.setSysTaskId(wfSystaskNow.getId());
                wfTask.setTaskExecutor(user.getId());
                List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
                wfTask.setId(wfTasks.get(0).getId());
                wfTask.setWfTaskRecord(wfSystaskNow.getSysTaskRecord());
                wfTask.setWfTaskState(WFTASKTWO);
                wfTask.setUpdateTime(getNow());
                wfTask.setUpdateUser(getUserId());
                wfTaskMapper.updateByPrimaryKeySelective(wfTask);
                int cId = getAddEntruts(user.getId(), wfTaskTest.getWfId());
                String mId = getEntruts(user.getId(), Integer.parseInt(wfTaskTest.getWfId()));
                if (cId != 0) {
                    wfTask = new WfTask();
                    wfTask.setSysTaskId(wfSystaskNow.getId());
                    wfTask.setTaskExecutor(cId);
                    List<WfTask> wfTasks1 = wfTaskMapper.selectAll(wfTask);
                    wfTask.setId(wfTasks1.get(0).getId());
                    wfTask.setWfTaskRecord(wfSystaskNow.getSysTaskRecord());
                    wfTask.setWfTaskState(WFTASKTWO);
                    wfTask.setUpdateTime(getNow());
                    wfTask.setUpdateUser(getUserId());
                    wfTaskMapper.updateByPrimaryKeySelective(wfTask);
                }
                if (mId != "") {
                    wfTask = new WfTask();
                    wfTask.setSysTaskId(wfSystaskNow.getId());
                    wfTask.setTaskExecutor(Integer.valueOf(mId));
                    List<WfTask> wfTasks1 = wfTaskMapper.selectAll(wfTask);
                    wfTask.setId(wfTasks1.get(0).getId());
                    wfTask.setWfTaskRecord(wfSystaskNow.getSysTaskRecord());
                    wfTask.setWfTaskState(WFTASKTWO);
                    wfTask.setUpdateTime(getNow());
                    wfTask.setUpdateUser(getUserId());
                    wfTaskMapper.updateByPrimaryKeySelective(wfTask);
                }
                wfSystaskNow.setUpdateTime(getNow());
                wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
                list.add("bin");
                WfTargetActivityAndOperators temp = new WfTargetActivityAndOperators();
                temp.setOperatorList(list);
                wfTargets.add(temp);

            }

        } else {
            // 3-抢占, 4-协作
            wfTargets = getAllNextTargetOperator(wfSystaskNow, wfTaskTest.getWfRecord());
            saveSub(wfTargets);
        }
        return wfTargets;
    }

    /*
     * 提交核心
     * */
    @Transactional
    public void saveSub(List<WfTargetActivityAndOperators> wfTargets) throws Exception {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        // 拿到一个活动直接提交
        WfTargetActivityAndOperators wfTargetActivityAndOperators = new WfTargetActivityAndOperators();
        if (wfTargets.size() == 1) {
            wfTargetActivityAndOperators = wfTargets.get(0);
            if (END.equals(wfTargetActivityAndOperators.getWfActivity().getActivityCode())) {
                saveEndTask(wfTargetActivityAndOperators, wfSystaskNow);
            } else {
                if (wfTargets.get(0).getOperatorList().size() == 0) return;
                wfSystaskNext = new WfSystask();
                wfSystaskNext.setRecentlySysTaskId(wfSystaskNow.getId());
                wfSystaskNext.setCreateTime(new Date(new Date().getTime() + 1));
                wfSystaskNext.setActivityId(wfTargetActivityAndOperators.getWfActivity().getWfaId());
                wfSystaskNext.setSysTaskKeyId(wfSystaskNow.getSysTaskKeyId());
                wfSystaskNext.setSysTaskState(DONEONE);
                wfSystaskNext.setWfTitle(wfSystaskNow.getWfTitle());
                wfSystaskNext.setSysTaskRecord(wfSystaskNow.getSysTaskRecord());
                List<String> list = wfTargets.get(0).getOperatorList();
                String users = "";
                for (Object obj : list) {
                    SysUser sysUser = (SysUser) obj;
                    users = users + sysUser.getId() + ",";
                }
                users = users.substring(0, users.length() - 1);
                wfSystaskNext.setTaskTodoUser(users);
                wfSystaskNext.setTaskDoneType(DONEONE);
                wfSystaskNext.setCreateTime(getNow());
                wfSystaskMapper.insertSelective(wfSystaskNext);
                wfSystaskNext.setId(wfSystaskMapper.lastInsertId());
                wfTask = new WfTask();
                wfTask.setSysTaskId(wfSystaskNow.getId());
                List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
                //提交时改变wfTask的数据
                if (wfTasks != null) {
                    for (int i = 0; i < wfTasks.size(); i++) {
                        wfTask.setId(wfTasks.get(i).getId());
                        wfTask.setWfTaskState(WFTASKTWO);
                        wfTask.setUpdateTime(getNow());
                        wfTask.setUpdateUser(getUserId());
                        wfTaskMapper.updateByPrimaryKeySelective(wfTask);
                    }
                }
                wfTask = new WfTask();
                wfTask.setActivityId(wfTargetActivityAndOperators.getWfActivity().getWfaId());
                wfTask.setSysTaskId(wfSystaskNext.getId());
                wfTask.setSysTaskKeyId(wfSystaskNext.getSysTaskKeyId());
                wfTask.setWfTitle(wfSystaskNext.getWfTitle());
                wfTask.setWfTaskRecord(wfSystaskNext.getSysTaskRecord());
                wfTask.setWfTaskState(WFTASKONE);
                wfTask.setCreateTime(getNow());
                SysUser sysUser = null;
                String optionType = getOperationType(wfTargetActivityAndOperators.getWfActivity().getWfaId());
                //判断下一环节操作类型
                if (OPERATION_ONE.equals(optionType)) {
                    List list1 = new ArrayList();
                    String[] ids = users.split(",");
                    wfTask.setTaskExecutor(Integer.valueOf(ids[0]));
                    wfTaskMapper.insertSelective(wfTask);
                    SysUser sysUser1 = new SysUser();
                    sysUser1 = sysUserMapper.selectById(Integer.valueOf(ids[0]));
                    WfTargetActivityAndOperators wf = new WfTargetActivityAndOperators();
                    if (wfTargets.get(0).getOperatorList().size() == 0) {
                        list1.add(sysUser1);
                        wf.setOperatorList(list1);
                        wfTargets.add(wf);
                    } else {
                        list1.add(sysUser1);
                        wfTargets.get(0).setOperatorList(list1);
                    }
                } else {
                    for (Object obj : list) {
                        sysUser = (SysUser) obj;
                        wfTask.setTaskExecutor(sysUser.getId());
                        wfTask.setCreateTime(getNow());
                        wfTaskMapper.insertSelective(wfTask);
                        wfSystaskKey = selectByPrimaryKey(wfSystaskNext.getSysTaskKeyId());
                        String enId = getEntruts(wfTask.getTaskExecutor(), wfSystaskKey.getWfId());
                        if (!"".equals(enId)) {
                            wfTask.setTaskExecutor(Integer.valueOf(enId));
                            wfTaskMapper.insertSelective(wfTask);//下一活动
                        }

                    }
                }
                WfSystaskKey wfSystaskKey1 = new WfSystaskKey();
                wfSystaskKey1 = selectByPrimaryKey(wfSystaskNext.getSysTaskKeyId());
                wfSystaskKey.setCurrentSysTaskId(wfSystaskNext.getId());
                if (wfSystaskKey1 != null) {
                    updateByPrimaryKeySelective(wfSystaskKey);
                    wfSystaskKey = selectByPrimaryKey(wfSystaskNext.getSysTaskKeyId());
                    wfSystaskNow.setUpdateTime(getNow());
                    wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
                } else {
                    insertSelective(wfSystaskKey);
                    wfSystaskKey = selectByPrimaryKey(wfSystaskMapper.lastInsertId());
                    wfSystaskNow.setCreateTime(getNow());
                    wfSystaskMapper.insertSelective(wfSystaskNow);
                }
            }
            ffDataIo(wfSystaskNow, wfSystaskKey.getWfId(), wfSystaskKey.getId());


        } else if (wfTargets.size() > 1) {
            session.setAttribute("wfSystaskNow", wfSystaskNow);
            session.setAttribute("wfSystaskKey", wfSystaskKey);
            if (!"".equals(wfTaskTe.getTaskId()) && wfTaskTe.getTaskId() != null) {
                wfSystaskNow.setSysTaskState(SYSTASKONE);
                wfSystaskNow.setUpdateTime(getNow());
                wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
            } else {
                wfSystaskMapper.deleteByPrimaryKey(wfSystaskNow.getId());
                deleteByPrimaryKey(wfSystaskKey.getId());
            }

        } else {
            session.setAttribute("wfSystaskNow", wfSystaskNow);
            session.setAttribute("wfSystaskKey", wfSystaskKey);
            if (!"".equals(wfTaskTe.getTaskId()) && wfTaskTe.getTaskId() != null) {
                wfSystaskNow.setSysTaskState(SYSTASKONE);
                wfSystaskNow.setUpdateTime(getNow());
                wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
            } else {
                wfSystaskMapper.deleteByPrimaryKey(wfSystaskNow.getId());
                deleteByPrimaryKey(wfSystaskKey.getId());
            }
        }
    }

    /*
     * 结束环节操作
     * */
    @Transactional
    public void saveEndTask(WfTargetActivityAndOperators wfTargetActivityAndOperators, WfSystask wfSystask) {
        wfSystaskNext = new WfSystask();
        SysUser user = UserUtil.getUser();
        wfSystaskNext.setSysTaskState(SYSTASKTWO);
        wfSystaskNext.setSysTaskKeyId(wfSystaskNow.getSysTaskKeyId());
        wfSystaskNext.setWfTitle(wfSystaskNow.getWfTitle());
        wfSystaskNext.setRecentlySysTaskId(wfSystaskNow.getId());
        wfSystaskNext.setSysTaskRecord(wfSystaskNow.getSysTaskRecord());
        wfSystaskNext.setTaskDoneUser(String.valueOf(user.getId()));
        wfSystaskNext.setActivityId(wfTargetActivityAndOperators.getWfActivity().getWfaId());
        wfSystaskNext.setCreateTime(getNow());
        wfSystaskMapper.insertSelective(wfSystaskNext);
        wfSystaskNext.setId(wfSystaskMapper.lastInsertId());
        wfSystaskNow.setUpdateTime(getNow());
        wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
        wfSystaskKey = new WfSystaskKey();
        wfSystaskKey = selectByPrimaryKey(wfSystask.getSysTaskKeyId());
        wfSystaskKey.setSysTaskKeyState(STATE_OVER);
        updateByPrimaryKeySelective(wfSystaskKey);
        wfTask = new WfTask();
        wfTask.setSysTaskKeyId(wfSystaskNow.getSysTaskKeyId());
        List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
        //提交时改变wfTask的数据
        if (wfTasks != null) {
            for (int i = 0; i < wfTasks.size(); i++) {
                wfTask.setId(wfTasks.get(i).getId());
                wfTask.setWfTaskState(WFTASKTWO);
                wfTask.setUpdateTime(getNow());
                wfTask.setUpdateUser(getUserId());
                wfTaskMapper.updateByPrimaryKeySelective(wfTask);
            }
        }
        //结束后发送结果
        saveWfTaskByEnd(wfSystaskNext);
    }

    /*
     * 结束后发送结果
     * */
    @Transactional
    public void saveWfTaskByEnd(WfSystask systask) {
        WfActivity wfActivity = new WfActivity();
        SysUser user = UserUtil.getUser();
        wfActivity = wfActivityMapper.selectByPrimaryKey(systask.getActivityId());
        wfTask = new WfTask();
        wfTask.setWfTitle(wfSystaskKey.getWfTitle());
        wfTask.setSysTaskKeyId(wfSystaskKey.getId());
        wfTask.setWfTaskRecord(wfSystaskNow.getSysTaskRecord());
        wfTask.setWfTaskState(WFTASKONE);
        wfTask.setActivityId(wfActivity.getWfaId());
        wfTask.setSysTaskId(systask.getId());
        if (ACTYPEONE.equals(wfActivity.getParticipateType())) {
            wfTask.setTaskExecutor(wfSystaskKey.getCreateUser());
            wfTask.setCreateTime(getNow());
            wfTaskMapper.insertSelective(wfTask);
        } else {
            wfSystaskNext = new WfSystask();
            wfSystaskNext.setSysTaskKeyId(systask.getSysTaskKeyId());
            List<WfSystask> wfSystasks = wfSystaskMapper.selectAll(wfSystaskNext);
            List<Integer> list = new ArrayList<>();
            for (WfSystask wfSystask : wfSystasks) {
                if ("".equals(wfSystask.getTaskDoneUser()) || wfSystask.getTaskDoneUser() == null) continue;
                String[] ids = wfSystask.getTaskDoneUser().split(",");
                if (ids.length > 1) {
                    for (int i = 0; i < ids.length; i++) {
                        list.add(Integer.valueOf(ids[i]));
                    }
                } else {
                    list.add(Integer.valueOf(wfSystask.getTaskDoneUser()));
                }
            }
            /*
             * 去重
             * 去掉最后一个办理人 （当前登陆人）
             * */
            for (int i = 0; i < list.size() - 1; i++) {
                for (int j = list.size() - 1; j > i; j--) {
                    if (list.get(j).equals(list.get(i))) {
                        list.remove(j);
                    }
                }
            }
            list.remove(user.getId());
            if (list.size() == 0) return;
            for (int q = 0; q < list.size(); q++) {
                wfTask.setTaskExecutor(list.get(q));
                wfTask.setCreateTime(getNow());
                wfTaskMapper.insertSelective(wfTask);
            }

        }

    }

    /*
     * 根据活动id判断活动操作类型：1-串行，2-并行, 3-抢占, 4-协作
     *
     * */
    @Transactional
    public String getOperationType(int activityId) {
        String operation = "";
        WfActivity wfActivity = wfActivityMapper.selectByPrimaryKey(activityId);
        operation = wfActivity.getOperationType();
        return operation;
    }

    //    根据wfID查到wf_workFlow
    public WfWorkflow getWorkflow(int id) {
        WfWorkflow wfWorkflow = new WfWorkflow();
        wfWorkflow = wfWorkflowMapper.selectByPrimaryKey(id);
        return wfWorkflow;
    }

    /*
     *根据源节点、表单内容查询所有目标节点和目标users
     * */
    @Transactional
    public List<WfTargetActivityAndOperators> getAllNextTargetOperator(WfSystask sysTask, String formJson) {
        List<WfTargetActivityAndOperators> result = new ArrayList<>();

        List<WfActivity> allTargetActivity = getAllTargetActivity(sysTask.getActivityId(), formJson);

        for (WfActivity targetActivity : allTargetActivity) {
            WfTargetActivityAndOperators singleActivityAndOperator = new WfTargetActivityAndOperators();

            List userList = getActivityOperator(sysTask, targetActivity.getWfaId());


            singleActivityAndOperator.setWfActivity(targetActivity);
            singleActivityAndOperator.setOperatorList(userList);

            result.add(singleActivityAndOperator);
        }

        return result;
    }

    /*
     *根据源节点查询所有目标节点
     * */
    @Transactional
    public List<WfActivity> getAllTargetActivity(int activityID, String jsonContent) {
        List<WfActivity> result = new ArrayList<>();

        WfActivityLine conLine = new WfActivityLine();
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        List<String> targetIds = new ArrayList<>();

        //根据sourceActivity找出所有的控制线

        conLine.setSourceId(activityID);
//        List<WfActivityLine> lineList = this.getAll(conLine);
        List<WfActivityLine> lineList = wfActivityLineMapper.selectAll(conLine);

        if (lineList.size() > 0) {
            //循环targetList，找出符合条件的第一个WfNextActivity
            for (WfActivityLine line : lineList) {
                String iFormula = line.getConditions();

                //判断流程线是否设置了控制条件
                if (iFormula == null || iFormula == "" || iFormula == "[]" || iFormula.equals("[]")) {
                    //如果没有控制条件
                    targetIds.add(String.valueOf(line.getTargetId()));
                } else {
                    boolean isPass = false;
                    //如果有控制条件
                    //解析每条流程线的控制条件
                    List<Map<String, String>> lineConditions = new ArrayList<>();
                    Gson gson = new Gson();
                    lineConditions = gson.fromJson(line.getConditions(), new TypeToken<List>() {
                    }.getType());

                    //循环流程线的每个控制条件
                    for (Map<String, String> condition : lineConditions) {

                        String formValue = this.getValueWithFormField(condition.get("fieldName"), jsonContent);
                        if (formValue == "") break;
                        String strFormula = formValue;
                        String operator = "";
                        switch (condition.get("operator")) {
                            case ("o11"):
                                operator = "==";
                                break;
                            case ("o22"):
                                operator = "!=";
                                break;
                            case ("o21"):
                                operator = ">";
                                break;
                            case ("o212"):
                                operator = ">=";
                                break;
                            case ("o12"):
                                operator = "<";
                                break;
                            case ("o121"):
                                operator = "<=";
                                break;
                        }
                        strFormula += operator;
                        strFormula += condition.get("conValue");

                        try {
                            isPass = (boolean) jse.eval(strFormula);
                        } catch (ScriptException e) {
                            e.printStackTrace();
                        }

                        if (!isPass) break;
                    }

                    if (isPass) {
                        targetIds.add(String.valueOf(line.getTargetId()));
                    }
                }
            }

            if (targetIds.size() > 0) {
                for (String targetId : targetIds) {
//                    result.add(wfActivityService.findById(targetId));
                    result.add(wfActivityMapper.selectByPrimaryKey(Integer.valueOf(targetId)));
                }
            }

        }

        return result;
    }

    /*
     *根据活动（activityID）查询所有用户
     * */
    @Transactional
    public List<SysUser> getActivityOperator(WfSystask currentSysTask, int otherActivityID) {
        List<SysUser> ret = new ArrayList<SysUser>();

        WfActivityAuthority wfActivityAuthority = new WfActivityAuthority();
        wfActivityAuthority.setActivityId(otherActivityID);
        List<WfActivityAuthority> targetAuthorityList = wfActivityAuthority.selectList(new QueryWrapper<WfActivityAuthority>().setEntity(wfActivityAuthority));

        List<Integer> userIds = new ArrayList<>();        //5用户
        List<Integer> dutyIds = new ArrayList<>();        //4角色
        List<Integer> postIds = new ArrayList<>();        //3岗位
        List<Integer> orgIds = new ArrayList<>();         //1机构
        List<Integer> logicIds = new ArrayList<>();       //6逻辑用户
        Integer appointSegment = 0; //7指定环节办理人

        if (targetAuthorityList.size() > 0) {
            for (WfActivityAuthority itemAuthority : targetAuthorityList) {
                switch (itemAuthority.getActivityType()) {
                    case ACTIVITY_TYPE_ORG:
//                        orgIds = String.valueOf(itemAuthority.getRole());
                        orgIds.add(itemAuthority.getRole());
                        break;
                    case ACTIVITY_TYPE_POST:
                        postIds.add(itemAuthority.getRole());
                        break;
                    case ACTIVITY_TYPE_DUTY:
                        dutyIds.add(itemAuthority.getRole());
                        break;
                    case ACTIVITY_TYPE_USER:
                        userIds.add(itemAuthority.getRole());
                        break;
                    case ACTIVITY_TYPE_LOGIC:
                        logicIds.add(itemAuthority.getRole());
                        break;
                    case ACTIVITY_TYPE_SEGMENT:
                        appointSegment = itemAuthority.getRole();
                        break;
                }
            }
        }
        WfActivity wfActivity = wfActivityMapper.selectByPrimaryKey(otherActivityID);
        ret = getSysUserByMultiRule(userIds, dutyIds, postIds, orgIds, logicIds, appointSegment, currentSysTask, wfActivity);

        return ret;
    }

    /*
     *根据字段名查找表单对应的值
     * */
    @Transactional
    public String getValueWithFormField(String fieldName, String contentJson) {

        List<FormElement> arrFields = new ArrayList<FormElement>();
        String result = "";
        arrFields = FormElementUtil.getDbFormElements(contentJson);
        List<FormElement> allFields = new ArrayList<FormElement>();

        for (FormElement field : arrFields) {
            if ("opinion".equals(field.getObjType())) {
                List<FormElement> arrFields1 = new ArrayList<FormElement>();
                arrFields1 = field.getNewOpinion();
                for (FormElement field1 : arrFields1) {
                    allFields.add(field1);
                }
            } else {
                allFields.add(field);
            }
        }

        for (FormElement field : allFields) {
            if (fieldName.equals(field.getName())) {
                if (field.getValues().size() == 1) {
                    if (field.getValueCodes().size() == 1) {
                        result = field.getValueCodes().get(0);
                    } else {
                        result = field.getValues().get(0);
                    }
                } else {
                    //复选框时，field.getValues().size() > 1
                }
            }
        }
        return result;
    }


    /*
     * @author: wj
     * @description: 获取下一环节处理人员集合
     * @date: 2019/3/19 11:26
     * @param   userIds：指定人员、roleIds：指定角色、postIds：指定岗位、orgIds：指定机构、logicIds：需要计算的指定人员、appointSegment：指定环节处理的环节id、wfSystask：当前环节实例数据
     * @return
     */
    @Transactional
    public List<SysUser> getSysUserByMultiRule(List<Integer> userList, List<Integer> dutyList, List<Integer> postList, List<Integer> orgList, List<Integer> logicList, Integer appointSegment, WfSystask wfSystask, WfActivity wfActivity) {

        List<SysUser> returnUserList = new ArrayList<SysUser>();
        List<SysUser> tempUserList = new ArrayList<SysUser>();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        //处理指定机构、职务、岗位、角色、人员的办理人员
        if (userList.size() > 0 ||
                dutyList.size() > 0 ||
                postList.size() > 0 ||
                orgList.size() > 0) {
            tempUserList = sysOrgExtendMapper.selectUserListByActivity(wfActivity.getWfaId());
        }
        if (wfActivity != null) {
            if ("1".equals(wfActivity.getOperationType()) && "2".equals(wfActivity.getParticipateType())) { //多人串行
                if (userList != null && userList.size() > 0) {
                    for (Integer eveUserId : userList) {
                        for (SysUser eveSysUserVO : tempUserList) {
                            if (eveUserId == eveSysUserVO.getId()) {
                                returnUserList.add(eveSysUserVO);
                                break;
                            }
                        }
                    }
                }
            } else {
                returnUserList.addAll(tempUserList);
            }
        }

        List<SysUser> doneUserList = new ArrayList<SysUser>();
        //处理需要计算的环节处理人
        if (logicList.size() > 0) {
            for (Integer item : logicList) {
                List<SysUser> eveLogicUserList = new ArrayList<SysUser>();   //如果有其他需要计算的存储在这个集合

                SysUser loginSysUser = UserUtil.getUser();
                SysOrg sysOrg = new SysOrg();
                SysPostUser sysPostUser = new SysPostUser();

                sysPostUser.setUserId(loginSysUser.getId());
                sysPostUser.setMainFlag(1);
                sysPostUser = sysPostUser.selectOne(new QueryWrapper<SysPostUser>().setEntity(sysPostUser));

                sysOrg.setId(sysPostUser.getOrgId());
                sysOrg = sysOrg.selectById();

                SysPost sysPost = new SysPost();

                if (item == 1) {   //发起人
                    WfSystaskKey wfSystaskKey = selectByPrimaryKey(wfSystask.getSysTaskKeyId());
                    if (wfSystaskKey != null && wfSystaskKey.getCreateUser() != null) {
                        SysUser sysUser = new SysUser();
                        sysUser = sysUserMapper.selectById(wfSystaskKey.getCreateUser());
                        if (sysUser != null) doneUserList.add(sysUser);
                    }
                } else if (item == 2) { //表单指定用户
                    List<FormElement> recordList = FormElementUtil.getDbFormElements(wfSystask.getSysTaskRecord());
                    if (recordList != null && recordList.size() > 0) {
                        String userId = "";
                        for (FormElement eveFormElement : recordList) {
                            if ("todouser".equals(eveFormElement.getObjType())) {
                                if (eveFormElement.getValueCodes().size() > 0) {
                                    userId = eveFormElement.getValueCodes().get(0);
                                    break;
                                }
                            }
                        }
                        if (userId.length() > 0) {
                            SysUser sysUser = new SysUser();
                            sysUser = sysUserMapper.selectById(wfSystaskKey.getCreateUser());
                            if (sysUser != null) {
                                doneUserList.add(sysUser);
                            }
                        }
                    }
                } else if(item == 3) {  //发起人部门经理
                    sysPost.setOrgId(sysOrg.getId());
                    sysPost.setDutyId(7);
                    sysPost = sysPost.selectOne(new QueryWrapper<SysPost>().setEntity(sysPost));

                    sysPostUser = new SysPostUser();
                    sysPostUser.setOrgId(sysOrg.getId());
                    sysPostUser.setPostId(sysPost.getId());
                    sysPostUser.setState(1);
                    List<SysPostUser> spuList = sysPostUser.selectList(new QueryWrapper<SysPostUser>().setEntity(sysPostUser));

                    for(SysPostUser spu : spuList){
                        SysUser su = new SysUser();
                        su.setId(spu.getUserId());
                        su = su.selectById();
                        doneUserList.add(su);
                    }

                } else if(item == 4) {  //发起人部门经理
                    sysPost.setOrgId(sysOrg.getId());
                    sysPost.setDutyId(6);
                    sysPost = sysPost.selectOne(new QueryWrapper<SysPost>().setEntity(sysPost));

                    sysPostUser = new SysPostUser();
                    sysPostUser.setOrgId(sysOrg.getId());
                    sysPostUser.setPostId(sysPost.getId());
                    sysPostUser.setState(1);
                    List<SysPostUser> spuList = sysPostUser.selectList(new QueryWrapper<SysPostUser>().setEntity(sysPostUser));

                    for(SysPostUser spu : spuList){
                        SysUser su = new SysUser();
                        su.setId(spu.getUserId());
                        su = su.selectById();
                        doneUserList.add(su);
                    }

                }

                if (eveLogicUserList.size() > 0) doneUserList.addAll(eveLogicUserList);
            }

        }
        //处理指定环节办理人
        if (appointSegment != 0) {
            doneUserList.addAll(sysOrgExtendMapper.selectUserListByActivity(appointSegment));
        }

        if (returnUserList.size() > 0) {
            if (doneUserList.size() > 0) {
                for (SysUser eveSysUserVO : doneUserList) {
                    boolean notExsit = true;
                    for (SysUser eveReturnSysUserVO : returnUserList) {
                        if (eveSysUserVO.getId().equals(eveReturnSysUserVO.getId())) {
                            notExsit = false;
                            break;
                        }
                    }
                    if (notExsit) returnUserList.add(eveSysUserVO);
                }
            }
        } else {
            if (doneUserList.size() > 0) returnUserList.addAll(doneUserList);
        }

        return returnUserList;
    }

    /*
     * sys_task_record加工
     * */
    @Transactional
    public String getTaskRecord(String record, String newrecord) {
        String taskRecord = "";
        List<FormElement> formElements = FormElementUtil.getDbFormElements(record);
        List<FormElement> newformElements = FormElementUtil.getDbFormElements(newrecord);
        List<FormElement> fs = new ArrayList<>();

        for (FormElement formElement : formElements) {
            if ("opinion".equals(formElement.getObjType())) {
                for (FormElement temp : newformElements) {
                    if (formElement.getName().equals(temp.getName())) {
                        List<String> ol = temp.getOldOpinion();
                        formElement.setOldOpinion(ol);
                        formElement.setNewOpinion(temp.getNewOpinion());
                    }
                }
            } else {
                for (FormElement temp : newformElements) {
                    if ("opinion".equals(temp.getObjType()) && !formElement.getName().equals(temp.getName())) {
                        boolean flag = true;
                        for (FormElement f : fs) {
                            if (f.getName().equals(temp.getName())) {
                                flag = false;
                                break;
                            }
                        }
                        if (flag) {
                            fs.add(temp);
                        }
                    } else if (formElement.getName().equals(temp.getName())) {
                        formElement = temp;
                    }
                }
            }

            fs.add(formElement);
        }
        Gson gson = new Gson();
        taskRecord = gson.toJson(fs);
        return taskRecord;
    }

    /*
     * 抢占：判断是否已经有人打开了审批 有：自己打不开审批 无：删除其他人的记录
     * true 可以打开
     * */
    @Transactional
    public boolean delByOptionType(int sysTaskId) {
        boolean flag = false;
        SysUser user = UserUtil.getUser();
        int userId = user.getId();
        wfTask = new WfTask();
        wfTask.setSysTaskId(sysTaskId);
        wfTask.setWfTaskState(1);
        List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
        if (wfTasks.size() == 1) {
            if (userId == wfTasks.get(0).getTaskExecutor()) {
                flag = true;
            } else {
                flag = false;
            }
        } else if (wfTasks == null && wfTasks.size() == 0) {
            flag = false;
        } else {
            for (WfTask wfTask : wfTasks) {
                if (userId == wfTask.getTaskExecutor()) {
                    flag = true;
                } else {
                    wfTask.setWfTaskState(2);
                    wfTask.setUpdateTime(getNow());
                    wfTask.setUpdateUser(getUserId());
                    wfTaskMapper.updateByPrimaryKeySelective(wfTask);
                }
            }
        }
        return flag;
    }

    /*
     * 异常提交  跳转提交
     * */
    @Transactional
    public List<WfTargetActivityAndOperators> saveWfNull(int taskId, int activityId) throws Exception {
        SysUser user = UserUtil.getUser();
        wfSystaskNow = new WfSystask();
        wfSystaskKey = new WfSystaskKey();
        if (taskId == 0) {
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            wfSystaskNow = (WfSystask) session.getAttribute("wfSystaskNow");
            wfSystaskKey = (WfSystaskKey) session.getAttribute("wfSystaskKey");
            wfSystaskNow.setCreateTime(getNow());
            wfSystaskMapper.insertSelective(wfSystaskNow);
            insertSelective(wfSystaskKey);
        } else {
            wfSystaskNow = wfSystaskMapper.selectByPrimaryKey(taskId);
        }
        if (wfSystaskNow.getTaskDoneUser() == null || "".equals(wfSystaskNow.getTaskDoneUser())) {
            wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
        }
        wfSystaskNow.setSysTaskState(SYSTASKTWO);
        WfActivity wfActivity = new WfActivity();
        wfActivity = wfActivityMapper.selectByPrimaryKey(activityId);
        WfTargetActivityAndOperators wfTargetActivityAndOperators = new WfTargetActivityAndOperators();
        wfTargetActivityAndOperators = getNextTarget(wfSystaskNow, wfActivity);
        List<WfTargetActivityAndOperators> wfTargets = new ArrayList<>();
        wfTargets.add(wfTargetActivityAndOperators);
        saveSub(wfTargets);
        return wfTargets;
    }

    /*   *根据源节点、表单内容查询目标节点和目标users
     */
    @Transactional
    public WfTargetActivityAndOperators getNextTarget(WfSystask sysTask, WfActivity wfActivity) {
        WfTargetActivityAndOperators result = new WfTargetActivityAndOperators();
        List userList = getActivityOperator(sysTask, wfActivity.getWfaId());
        result.setWfActivity(wfActivity);
        result.setOperatorList(userList);
        return result;
    }

    /*
     * 退回
     * */
    @Transactional
    public List<WfTargetActivityAndOperators> saveGoBack(WfTaskTest wfTaskTest) throws Exception {
        SysUser user = UserUtil.getUser();
        wfSystaskNow = new WfSystask();
        wfSystaskNow = wfSystaskMapper.selectByPrimaryKey(Integer.valueOf(wfTaskTest.getTaskId()));
        wfSystaskNext = wfSystaskMapper.selectByPrimaryKey(wfSystaskNow.getRecentlySysTaskId());
        wfSystaskNow.setSysTaskState(SYSTASKTWO);
        wfSystaskNow.setTaskDoneType(DONETWO);
        wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
        wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
        WfActivity wfActivity = new WfActivity();
        wfActivity = wfActivityMapper.selectByPrimaryKey(wfSystaskNext.getActivityId());
        WfTargetActivityAndOperators wfTargetActivityAndOperators = new WfTargetActivityAndOperators();
        wfTargetActivityAndOperators.setWfActivity(wfActivity);
        SysUser sysUser = new SysUser();
        wfSystaskNext = wfSystaskMapper.selectByPrimaryKey(wfSystaskNow.getRecentlySysTaskId());
        String id = wfSystaskNext.getTaskTodoUser();
        wfSystaskNext.setActivityId(wfActivity.getWfaId());
        List list = new ArrayList();
        String[] ids = id.split(",");
        if (ids.length > 1) {
            for (int i = 0; i < ids.length; i++) {
                sysUser = sysUserMapper.selectById(Integer.valueOf(ids[i]));
                list.add(sysUser);
            }
        } else {
            sysUser = sysUserMapper.selectById(Integer.valueOf(id));
            list.add(sysUser);
        }
        wfTargetActivityAndOperators.setOperatorList(list);
        List<WfTargetActivityAndOperators> wfTargets = new ArrayList<>();
        wfTargets.add(wfTargetActivityAndOperators);
        saveSub(wfTargets);
        return wfTargets;
    }

    /*撤销*/
    @Transactional
    public void saveRevoke(WfTaskTest wfTaskTest) throws Exception {
        SysUser user = UserUtil.getUser();
        wfSystaskNow = wfSystaskMapper.selectByPrimaryKey(Integer.valueOf(wfTaskTest.getTaskId()));
        wfSystaskNow.setSysTaskState(SYSTASKTWO);
        wfSystaskNow.setSysTaskRecord(wfTaskTest.getWfRecord());
        wfSystaskNow.setTaskDoneUser(String.valueOf(user.getId()));
        wfSystaskNow.setTaskDoneType(DONETHREE);
        wfSystaskKey = selectByPrimaryKey(wfSystaskNow.getSysTaskKeyId());
        wfSystaskKey.setCurrentSysTaskId(wfSystaskNow.getId());
        wfSystaskKey.setSysTaskKeyState(STATE_REVOKE);
        wfTask = new WfTask();
        wfTask.setSysTaskKeyId(wfSystaskNow.getSysTaskKeyId());
        List<WfTask> wfTasks = wfTaskMapper.selectAll(wfTask);
        //提交时改变wfTask的数据
        if (wfTasks != null) {
            for (int i = 0; i < wfTasks.size(); i++) {
                wfTask.setId(wfTasks.get(i).getId());
                wfTask.setWfTaskState(WFTASKTWO);
                wfTask.setUpdateTime(getNow());
                wfTask.setUpdateUser(getUserId());
                wfTaskMapper.updateByPrimaryKeySelective(wfTask);
            }
        }
        updateByPrimaryKeySelective(wfSystaskKey);
        wfSystaskNow.setUpdateTime(getNow());
        wfSystaskMapper.updateByPrimaryKeySelective(wfSystaskNow);
        ffDataIo(wfSystaskNow, Integer.parseInt(wfTaskTest.getWfId()), wfSystaskKey.getId());


    }

    /*
     * 判断并且拿到被委托人id
     * */
    @Transactional
    public String getEntruts(int id, int wfId) {
        String userId = "";
        WfEntrustVO entrust = new WfEntrustVO();
        entrust.setConsignor(id);
        entrust.setWfId(String.valueOf(wfId));
        List<WfEntrustVO> wfEntrustVOS = wfEntrustVOMapper.selectEntrustVO(entrust);
        if (wfEntrustVOS != null && wfEntrustVOS.size() != 0) {
            userId = String.valueOf(wfEntrustVOS.get(0).getMandatary());
        }
        return userId;
    }

    /*
     * 判断并且拿到委托人id
     * */
    public int getAddEntruts(int userId, String wfId) {
        int id = 0;
        WfEntrustVO entrust = new WfEntrustVO();
        entrust.setMandatary(userId);
        entrust.setWfId(wfId);
        List<WfEntrustVO> wfEntrustVOS = wfEntrustVOMapper.selectEntrustVO(entrust);
        if (wfEntrustVOS != null && wfEntrustVOS.size() != 0) {
            id = wfEntrustVOS.get(0).getConsignor();
        }
        return id;
    }


    /*
     * @author: wj
     * @description: 流程实例分页列表
     * @date: 2019/4/11 15:40
     * @param
     * @return
     */
    public List<WfSystaskKeyVO> selectAllVO(WfSystaskKeyVO wfSystaskKeyVO) {
        List<WfSystaskKeyVO> list = wfSystaskKeyVOMapper.selectAllVO(wfSystaskKeyVO);
        SysUser sysUser = new SysUser();
        sysUser.setUserState(1);
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserState, 1).orderByAsc(SysUser::getId));
        WfWorkflow wfWorkflow = new WfWorkflow();
        wfWorkflow.setWfId(wfSystaskKey.getWfId());
        List<WfWorkflow> workflowList = wfWorkflowMapper.selectAll(wfWorkflow);
        if (list != null && list.size() > 0) {
            for (WfSystaskKeyVO eveWfSystaskKey : list) {
                for (SysUser eveSysUser : userList) {
                    if (eveWfSystaskKey.getCreateUser().equals(eveSysUser.getId())) {
                        eveWfSystaskKey.setUserName(eveSysUser.getUserName());
                        break;
                    }
                }
                for (WfWorkflow eveWfWorkflow : workflowList) {
                    if (eveWfSystaskKey.getWfId().equals(eveWfWorkflow.getWfId())) {
                        eveWfSystaskKey.setWfName(eveWfWorkflow.getWfName());
                        break;
                    }
                }
            }
        }
        return list;
    }

    private String ApiName = "com.zimi.controller.%sApi";
    private String ModelName = "com.zimi.model.%s";

    // 往业务模块传递数据
    @Transactional
    public void ffDataIo(WfSystask sysTask, int wfId, int keyId) throws Exception {
        Map<String, Object> map = this.wfRecordToMap(sysTask.getSysTaskRecord());
        String entityName = StrUtil.first2up(Objects.requireNonNull(this.getModuleEnName(wfId)));
        Class<?> clazz = Class.forName(String.format(ApiName, entityName));
        Object obj = clazz.newInstance();
        Method method = null;
        Integer id = selectObj(map, String.format(ModelName, entityName), keyId);
        if (id == null) {
            map.put("wfId", keyId);
            method = clazz.getMethod("saveWfRecord", Map.class, Integer.class, Integer.class);
            method.invoke(obj, map, wfId, keyId);
        } else {
            method = clazz.getMethod("updateWfRecord", Map.class, Integer.class);
            method.invoke(obj, map, id);
        }
    }

    /**
     * 解析 wfRecord 到 map
     */
    private Map<String, Object> wfRecordToMap(String wfRecord) {
        Map<String, Object> result = new HashMap<>();
        List<FormElement> listRecord = FormElementUtil.getDbFormElements(wfRecord);
        List<String> tempValue = new ArrayList<>();
        StringBuffer strValue = new StringBuffer();

        for (FormElement formElement : listRecord) {
            strValue = new StringBuffer();
            if (formElement.getObjType() != null && "opinion".equals(formElement.getObjType())) {
                for (FormElement tmp : formElement.getNewOpinion()) {
                    if (tmp.getTagType() != null && "radio".equals(tmp.getTagType())) {
                        result.put(tmp.getName(), tmp.getValueCodes().get(0));
                    }
                }
            } else {
                if (formElement.getValueCodes().size() == 0 || formElement.getValueCodes() == null) {
                    tempValue = formElement.getValues();
                } else {
                    tempValue = formElement.getValueCodes();
                }

                for (String strTemp : tempValue) {
                    if (strValue.length() > 0) strValue.append(",");
                    strValue.append(strTemp);
                }

                result.put(formElement.getName(), strValue.toString());

            }
        }


        return result;
    }

    /**
     * 获取module en name
     */
    private String getModuleEnName(Integer wfid) {
        WfWorkflow temp1 = wfWorkflowMapper.selectByPrimaryKey(wfid);
        if (temp1 != null && temp1.getModuleId() != null) {
            WfModule temp2 = wfModuleMapper.selectByPrimaryKey(temp1.getModuleId());
            String result = temp2.getCodeName();

            String[] tempName = result.split("_");
            String conName = "";
            for (Integer k = 0; k < tempName.length; k++) {
                if (k == 0) {
                    conName = tempName[0];
                } else {
                    conName += tempName[k].substring(0, 1).toUpperCase() + tempName[k].substring(1);
                }
            }

            return conName;
        }
        return null;
    }

    //添加费用报销
    private void addExpenseReimbursement(Map<String, Object> map, Integer keyId) {
        ExpenseReimbursement er = new ExpenseReimbursement();
        String paid = "";
        Map<String, Object> beanMap = new HashMap<String, Object>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() + ",\t Value : " + entry.getValue());

            if ("erId".equals(entry.getKey())) {

            } else if ("erOrg".equals(entry.getKey())) {
                beanMap.put("erOrg", entry.getValue());
            } else if ("erDate".equals(entry.getKey())) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date d = sdf.parse(entry.getValue().toString());
                    beanMap.put("erDate", d);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if ("erUser".equals(entry.getKey())) {
                beanMap.put("erUser", entry.getValue());
            } else if ("amount".equals(entry.getKey())) {
                if (!entry.getValue().toString().equals("") && entry.getValue().toString() != null) {
                    beanMap.put("amount", Float.parseFloat(entry.getValue().toString()));
                }
            } else if ("amountCapital".equals(entry.getKey())) {
                beanMap.put("amountCapital", entry.getValue());
            } else if ("task".equals(entry.getKey())) {
                beanMap.put("task", entry.getValue());
            } else if (entry.getKey().indexOf("paid") > -1) {
                String[] keys = entry.getKey().split("-");
                if ("cash".equals(keys[1])) {
                    String key = "paid-" + "cash";
                    paid = paid + "现金：" + map.get(key) + ",";
                } else if ("bank".equals(keys[1])) {
                    String key = "paid-" + "bank";
                    paid = paid + "银行：" + map.get(key) + ",";
                } else if ("transfer".equals(keys[1])) {
                    String key = "paid-" + "transfer";
                    paid = paid + "转账：" + map.get(key) + ",";
                }
            } else if ("signature".equals(entry.getValue())) {
                beanMap.put("signature", entry.getValue());
            } else if ("financialAdvice".equals(entry.getValue())) {
                beanMap.put("financialAdvice", entry.getValue());
            } else if ("unitLeader".equals(entry.getValue())) {
                beanMap.put("unitLeader", Integer.parseInt(entry.getValue().toString()));
            } else if ("keepTheAcceptance".equals(entry.getValue())) {
                beanMap.put("keepTheAcceptance", entry.getValue());
            }
        }

        beanMap.put("paid", paid);
        beanMap.put("wfId", keyId);
        try {
            BeanUtils.populate(er, beanMap);
            List<ExpenseReimbursement> list = expenseReimbursementMapper.selectByWfId(keyId);
            if (list != null && list.size() > 0) {
                expenseReimbursementMapper.updateByPrimaryKeySelective(er);
            } else {
                expenseReimbursementMapper.insertSelective(er);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询
    public Integer selectObj(Map<String, Object> map, String className, Integer keyId) {
        Integer id = null;
        //根据类名创建对象
        try {
            //根据类名创建对象
            Class clazz = Class.forName(className);
            Object obj = clazz.newInstance();

            PropertyDescriptor pd1 = null;
            pd1 = new PropertyDescriptor("wfId", clazz);
            PropertyDescriptor pd2 = null;
            pd2 = new PropertyDescriptor("id", clazz);
            //获得get方法
            Method wM = pd1.getReadMethod();
            Method wM2 = pd2.getReadMethod();

            Method method = null;
            method = clazz.getMethod("selectAll");
            Object list = method.invoke(obj);
            for (Object o : (List) list) {
                Object wfid = wM.invoke(o);
                if (wfid == keyId || keyId.equals(wfid)) {
                    id = Integer.parseInt(wM2.invoke(o).toString());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return id;
    }


}
